#template
import sys
import os #os functions
import getopt #command line parser
import pdb #debug with pdb.set_trace()

import libUtilities
import libME

def main(argv):
	try:
		#pdb.set_trace()
		libUtilities.logEnabled = True

		opt,args = getopt.getopt(argv[1:],"xcl:fa:v:s:u:r:d:")
		
		libUtilities.Log()
		
		libME.CheckConfig()
		
		if len(opt) == 0:
			usage()
			exit(0)
		
		#pdb.set_trace()
		libUtilities.logEnabled = False
		for option in opt:
			if option[0] == "-x":
				libUtilities.logEnabled = True
			if option[0] == "-c":
				#pdb.set_trace()
				libUtilities.Log("-c option, downloading catalog")
				print "downloading catalog, please wait..."
				downloaded = libME.GetCatalog()
				libUtilities.Log("catalog count: %d series" % (len(downloaded)))
				print "Download finished."
				print "%d series found and saved" % (len(downloaded))
				break;
			if option[0] == "-l":
				#pdb.set_trace()
				print "Listing avaliable series."
				libUtilities.Log("-l option, listing from catalog, filter \"%s\"" % (option[1]))
				avaliable = libME.List(option[1])
				if avaliable == -1:
					libUtilities.Log("catalog file not found")
					print "Catalog file not found, download a new one (-d)"
					break;
				else:
					libUtilities.Log("\"%s\" returned %d results" % (option[1],len(avaliable)))
					print "Found %d series:" % (len(avaliable))
					print "------------------------------"
					i = 0
					for serie in avaliable:
						print "[%s] %s" % (str(serie[0]).zfill(5),serie[1])
					libUtilities.Log("results printed")
				break;
			if option[0] == "-f":
				#pdb.set_trace()
				libUtilities.Log("-f option, viewing following series")
				following = libME.Following()
				if len(following) == 0:
					libUtilities.Log("following list is empty")
					print "You are not following any serie"
				else:
					libUtilities.Log("following list has %d series" % (len(following)))
					print "Following %d series:" % (len(following))
					for serie in following.values():
						print "[%d] %s [%s]" % (serie.id,serie.name,str(serie.lastdownloaded) if int(serie.lastdownloaded) > -1 else "no chapters")
				libUtilities.Log("results printed")
				break;
			if option[0] == "-a":
				#pdb.set_trace()
				libUtilities.Log("-a option, adding serie with catalog_id: %s" % (option[1]))
				print "Adding serie [%s], please wait..." % (option[1])
				libUtilities.Log("loading serie from catalog")
				catalogSerie = libME.GetFromCatalog(int(option[1]))
				if catalogSerie == -1:
					libUtilities.Log("catalog not found")
					print "Directory file not found, download a new one (-d)"
					break
				elif catalogSerie == 0:
					libUtilities.Log("serie not found")
					print "Catalog id not found"
					break;
				else:
					if libUtilities.logEnabled:
						pdb.set_trace()
					libUtilities.Log("serie found")
					print catalogSerie[0],catalogSerie[1],catalogSerie[2]
					libUtilities.Log("retrieving serie info")
					serieInfo = libME.GetSerieInfo(catalogSerie[2])
					printSerie(serieInfo)
					libUtilities.Log("adding serier to following list")
					#pdb.set_trace()
					if len(args) > 0:
						done = libME.AddSerie(serieInfo,args[0])
					else:
						done = libME.AddSerie(serieInfo)
					if done == -1:
						libUtilities.Log("serie already in following list")
						print "Already following this serie"
					else:
						libUtilities.Log("serie added to following list")	
						print "Serie added!"
					break
				#serie can be in following list
				break;
			if option[0] == "-v":
				#pdb.set_trace()
				libUtilities.Log("- v option, viewing serie info for id %s" % (option[1]))
				print "Viewing serie [%s], please wait..." % (option[1])
				serieInfo = libME.ViewSerie(int(option[1]))
				if serieInfo == -1:
					libUtilities.Log("serie not found")
					print "Serie id not found"
				else:
					libUtilities.Log("info retrieved")
					printSerie(serieInfo)
					
				break
			if option[0] == "-s":
				#pdb.set_trace()
				libUtilities.Log("-s option, viewing serie chapters for id %s" % (option[1]))
				print "Viewing serie [%s] chapters, please wait..." % (option[1])
				chapters = libME.ViewSerieChapters(int(option[1]))
				if chapters == -1:
					libUtilities.Log("serie not found")
					print "Serie id not found"
				else:
					libUtilities.Log("info retrieved")
					for chapter in chapters:
						print "[%s] %s" % (chapter[0],chapter[2])
					
				break
			if option[0] == "-u":
				#pdb.set_trace(
				libUtilities.Log("-u option, updating serie %s" % (option[1]))
				if option[1] == "-1":
					libUtilities.Log("updating all series")
					print "Updating all series, please wait..."
				else:
					libUtilities.Log("updating serie %s" % (option[1]))
					print "Updating serie [%s], please wait..." % (option[1])
				serieInfo = libME.UpdateSerie(int(option[1]))
				if serieInfo == -1:
					libUtilities.Log("serie not found")
					print "Serie id not found"
				else:
					libUtilities.Log("finished update")
					for serie in serieInfo:
						printSerie(serie)
					
				break
			if option[0] == "-r":
				libUtilities.Log("-r option, removing serie %s" % (option[1]))
				if option[1] == "-1":
					libUtilities.Log("removing all series")
					print "Removing all series, please wait..."
				else:
					libUtilities.Log("removing serie %s" % (option[1]))
					print "Removing serie [%s], please wait..." % (option[1])
				removed = libME.RemoveSerie(int(option[1]))
				if removed == -1:
					libUtilities.Log("serie not found")
					print "Serie id not found"
				else:
					libUtilities.Log("finished removing")
					print "%d series removed" % (removed)
					
				break
			if option[0] == "-d":
				if libUtilities.logEnabled:
					pdb.set_trace()
				serie = int(option[1])
				start = 0
				end = 0
				libUtilities.Log("-d option, downloading serie %d with params \"%d\" and \"%d\"" % (serie,int(start),end))

				if serie == -1:
					#update all series from last downloaded to last avaliable
					libME.DownloadAllSeriesLastChapters()
					break;
				else:
					start = args[0]
					end = -1
					if len(args) > 1:
						end = int(args[1])
					if start == "a":
						#update serie from last downloaded to last avaliable
						libME.DownloadSerieLastChapters(serie)
					elif end >= 0:
						#update serie from start to end
						libME.DownloadSerieChapters(serie,int(start),end)
			elif option[0] != "-x": #-x option does not break loop
				usage()
				break;
		
		print ""
		libUtilities.logEnabled = True

		libUtilities.Log()
	except Exception as ex:
		libUtilities.logEnabled = True

		usage()
		libUtilities.Log("General error",ex)
		libUtilities.Log()

def printSerie(serieInfo):
	print "------------------------------------"
	print "ID:",serieInfo.id
	print "Name:",serieInfo.name
	print "Url:",serieInfo.url
	print "Last updated on:",serieInfo.lastupdated
	print "Last avaliable chapter:",serieInfo.lastavaliable
	print "Last downloaded chapter:",serieInfo.lastdownloaded
	print "Description:\n",serieInfo.description
	print "------------------------------------"


def usage():
	print "Usage:"
	print "%s -c(atalog)                               #downloads avaliable series to disk" % sys.argv[0]
	print "%s -l(ist) \"[<partial_name>]\"               #list downloaded series from catalog, if \"\" is empty, list all" % sys.argv[0]
	print "%s -f(ollowing)                             #list following series" % sys.argv[0]
	print "%s -a(dd) <catalog_id>                      #add <catalog_id> to following list" % sys.argv[0]
	print "%s -v(iew) <id>                             #views <id> info: name, description,url, last downloaded" % sys.argv[0]
	print "%s -s(how) <id>                             #shows <id> chapters"
	print "%s -u(pdate) [<id>]                         #gets updated info for a serie <id>, -1 updates all series" % sys.argv[0]
	print "%s -r(emove) [<id>]                         #remove <id> from following list" % sys.argv[0]
	print "%s -d(ownload) [<id>] [chapterA] [chapterB] #updates <id> downloading from [chapterA] to [chapterB] and zips them. If no chapter is given, lastdownload chapter will be used" % sys.argv[0]
	print ""
	
if __name__ == "__main__":
	main(sys.argv)
